//
//  JDTools.swift
//  DragonWallet
//
//  Created by volantPig on 2023/12/26.
//

import UIKit
import AVFoundation
import JGProgressHUD

func printLog<N>(_ message: N, fileName: String = #file, methodName: String = #function, lineNumber: Int = #line) {
    #if DEBUG
        let paths = fileName.components(separatedBy: "/")
        NSLog("[XLBApp] \(paths.last! as NSString) function:\(methodName) line:\(lineNumber) log: \(message) ")
    #endif
}

class JDTools: NSObject {
    
    class func checkToken() -> Bool {
        if (JDLoginModel.default.token ?? "").count == 0 {
            // 未登录
//            JDLoginModel.default.userLogout()
//            UserDefaults.standard.removeObject(forKey: "loginInfo")
                                    
            let loginVC = JDLoginViewController()
            let navigationLoginVC = UINavigationController(rootViewController: loginVC)
            JDTools.getKeyWindows()?.rootViewController?.present(navigationLoginVC, animated: true)
            return false
        }
        return true
    }
    
    
    /// 获取当前keyWindows
    class func getKeyWindows() -> UIWindow? {
        var window: UIWindow?
        if #available(iOS 13, *) {
            for windowScene in UIApplication.shared.connectedScenes where windowScene.isKind(of: UIWindowScene.self) {
                if windowScene.activationState == UIScene.ActivationState.foregroundActive
                {
                    let currentWindowsScene: UIWindowScene = windowScene as! UIWindowScene
                    window = currentWindowsScene.windows.first
                    break
                }
            }

        } else {
            window = UIApplication.shared.keyWindow
        }
        return window
    }
    
    class func showLoading() {
        
        
        
        
        
    }

    //获取当前时间戳
    class func currentTimeStamp() -> String {
        let now = Date()
        let timeInterval:TimeInterval = now.timeIntervalSince1970
        let timeStamp = Int(timeInterval)
        
        return String(timeStamp);
    }
    
    ///计算文字的宽高（非富文本文字）ps:size参数传 CGSize.init(width: screenWidth, height: 文字高度) 即可
    class func getTextRectSize(text: NSString,font: UIFont ,size: CGSize) -> CGRect {
        let attributes = [NSAttributedString.Key.font: font]
        let option = NSStringDrawingOptions.usesLineFragmentOrigin
        let rect:CGRect = text.boundingRect(with: size, options: option, attributes: attributes, context: nil)
        return rect
    }
    
    /// 转码
    // TODO: 弄个回调 成功上传 失败 提示
    class func transformMoive(inputPath:String, outputPath:String, completed:@escaping (URL) -> Void) {

            let avAsset = AVURLAsset(url: URL.init(fileURLWithPath: inputPath), options: nil)
            let assetTime = avAsset.duration

            let duration = CMTimeGetSeconds(assetTime)
            print("视频时长 \(duration)");
            let compatiblePresets = AVAssetExportSession.exportPresets(compatibleWith: avAsset)
            if compatiblePresets.contains(AVAssetExportPresetLowQuality) {
                let exportSession:AVAssetExportSession = AVAssetExportSession.init(asset: avAsset, presetName: AVAssetExportPresetMediumQuality)!
                let existBool = FileManager.default.fileExists(atPath: outputPath)
                if existBool {
                }
                exportSession.outputURL = URL.init(fileURLWithPath: outputPath)


                exportSession.outputFileType = AVFileType.mp4
                exportSession.shouldOptimizeForNetworkUse = true;
                exportSession.exportAsynchronously(completionHandler: {

                    switch exportSession.status{

                    case .failed:

                        print("失败...\(String(describing: exportSession.error?.localizedDescription))")
                        break
                    case .cancelled:
                        print("取消")
                        break;
                    case .completed:
                        print("转码成功")
                        let mp4Path = URL.init(fileURLWithPath: outputPath)
//                        self.uploadVideo(mp4Path: mp4Path)
                        completed(mp4Path)
                        break;
                    default:
                        print("..")
                        break;
                    }
                })
            }
    }
    
    class func getVideoThumbnail(url: URL) -> UIImage? {
        let asset = AVAsset(url: url)
        let assetImgGenerate = AVAssetImageGenerator(asset: asset)
        assetImgGenerate.appliesPreferredTrackTransform = true

        let time = CMTimeMakeWithSeconds(5.0, preferredTimescale: 600)

        do {
            let img = try assetImgGenerate.copyCGImage(at: time, actualTime: nil)
            let thumbnail = UIImage(cgImage: img)
            return thumbnail
        } catch {
            print(error.localizedDescription)
        }
        return nil
    }
    
    /// 使用颜色创建一个UIImage
    ///
    /// - Parameter color: 传入 UIcolor 类型参数，作为背景颜色
    /// - Returns: 返回 UIImage 类型对象
    class func customImageWithColor(color: UIColor, alpha: CGFloat = 1.0) -> UIImage {
        let rect = CGRect.init(x: 0, y: 0, width: 1, height: 1)
        UIGraphicsBeginImageContext(rect.size)
        let context = UIGraphicsGetCurrentContext()
        context?.setFillColor(color.cgColor)
        context?.setAlpha(alpha)
        context?.fill(rect)
        let image = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()
        return image!
    }
    
    /// 将UIView转换成UIImage，ps:UIView尺寸要确认
    /// - Parameter view: 想要变成图片的view
    /// - Returns: 这个方法，在富文本中使用时，会有黑色背景
    class func convertUIViewToUIImage(view: UIView) -> UIImage {
        var image = UIImage()
        //UIGraphicsBeginImageContextWithOptions(区域大小, 是否是非透明的, 屏幕密度)
//        UIGraphicsBeginImageContextWithOptions(view.frame.size, true, UIScreen.main.scale)
        UIGraphicsBeginImageContextWithOptions(CGSizeMake(view.frame.size.width-1, view.frame.size.height), true, UIScreen.main.scale)
        view.layer.render(in: UIGraphicsGetCurrentContext()!)
        view.layer.backgroundColor = UIColor.clear.cgColor
        image = UIGraphicsGetImageFromCurrentImageContext() ?? UIImage()
        UIGraphicsEndImageContext()
        return image
    }
}
